//
//  SettingViewController.m
//  YouthOlympic2014
//
//  Created by xiangpaopao on 14-7-1.
//  Copyright (c) 2014年 mitian. All rights reserved.
//

#import "SettingViewController.h"
#import "NSString+FontAwesome.h"
#import "UIView+WhenTappedBlocks.h"
#import "AlertService.h"
#import "HelpViewController.h"
#import "ASIHTTPRequest.h"
#import "DDXML.h"
#import "DDXMLElementAdditions.h"
#import "AppDelegate.h"

#define PickerTagEvent 1000
#define PickerTagDaily 2000


@interface SettingViewController ()

@property (nonatomic, strong) IBOutlet UIView *shadeView;
@property (nonatomic, strong) IBOutlet UIView* activityView;
@property (nonatomic, getter = isShowing) BOOL show;

@property (nonatomic, strong)IBOutlet UISwitch *isDailySwitch;
@property (nonatomic, strong)IBOutlet UISwitch *isEventSwitch;

@property (nonatomic, strong)IBOutlet UILabel *vLabel;
@property (nonatomic, strong)NSString *app_Version;

@property (nonatomic)IBOutlet UIButton *dailyTitleBtn;
@property (nonatomic)IBOutlet UIButton *eventTitleBtn;
@property (nonatomic)IBOutletCollection(UIButton) NSArray *dailyItems;
@property (nonatomic)IBOutletCollection(UIButton) NSArray *eventItems;

@end

@implementation SettingViewController



- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
   [self setupLeftButton];
   [self setupActivityView];
    
    [self.isDailySwitch setOn:[AlertService isDailyAlertOn]];
    [self.isEventSwitch setOn:[AlertService isEventAlertOn]];
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    self.app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    [self.vLabel setText:self.app_Version];
    
    
    //很奇怪，从IBOutletCollection取出元素时，索引是无序的，不知道是不是bug，要自己排一下旭
    self.dailyItems = [self.dailyItems sortedArrayUsingComparator:^NSComparisonResult(id label1, id label2) {
        if ([label1 frame].origin.y < [label2 frame].origin.y) return NSOrderedAscending;
        else if ([label1 frame].origin.y > [label2 frame].origin.y) return NSOrderedDescending;
        else return NSOrderedSame;
    }];
    self.eventItems = [self.eventItems sortedArrayUsingComparator:^NSComparisonResult(id label1, id label2) {
        if ([label1 frame].origin.y < [label2 frame].origin.y) return NSOrderedAscending;
        else if ([label1 frame].origin.y > [label2 frame].origin.y) return NSOrderedDescending;
        else return NSOrderedSame;
    }];
    
    
    NSString *dailyTitle = [[AlertService sharedCenter] getDailyAlertTime];
    NSString *eventTitle = [[AlertService sharedCenter] getEventAheadTime];
    
    [self.eventTitleBtn setTitle:[NSString stringWithFormat:NSLocalizedString(@"提前%@分钟提醒", nil),eventTitle] forState:UIControlStateNormal];
    [self.dailyTitleBtn setTitle:[NSString stringWithFormat:@"%@ AM",dailyTitle] forState:UIControlStateNormal];
    
    
    for(int i = 0;i<3;i++){
        UIButton *aButton = [self.eventItems objectAtIndex:i];
        [aButton setTitle:[NSString stringWithFormat:NSLocalizedString(@"提前%@分钟提醒", nil),[self titleForEventAtRow:i]] forState:UIControlStateNormal];
        [aButton setTag:PickerTagEvent+i];
        if ([eventTitle isEqualToString:[self titleForEventAtRow:i]]) {
            [aButton setSelected:YES];
        }
    }
    
    for(int i = 0;i<3;i++){
        UIButton *aButton = [self.dailyItems objectAtIndex:i];
        [aButton setTitle:[NSString stringWithFormat:@"%@ AM",[self titleForDailyAtRow:i]] forState:UIControlStateNormal];
        [aButton setTag:PickerTagDaily+i];
        if ([dailyTitle isEqualToString:[self titleForDailyAtRow:i]]) {
            [aButton setSelected:YES];
        }
    }
    
    
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
	[self.navigationController.view addSubview:HUD];
	HUD.delegate = self;
}



-(void)viewWillAppear:(BOOL)animated
{
    
}

-(void)setupLeftButton{
    UIButton* leftButton= [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [leftButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [leftButton.titleLabel setFont:[UIFont fontWithName:kFontAwesomeFamilyName size:26]];
    [leftButton setTitle:[NSString fontAwesomeIconStringForIconIdentifier:@"fa-angle-left"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(leftButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftDrawerButton = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    
    [self.navigationItem setLeftBarButtonItem:leftDrawerButton animated:YES];
}


-(void)leftButtonPress:(id)sender{
    
    [self.navigationController dismissViewControllerAnimated:YES completion:^{}];
}


-(IBAction)pickAct:(id)sender
{
    UIButton *aButton = sender;
    
    if (aButton.tag>=PickerTagDaily) {
        NSString *val = [self titleForDailyAtRow:aButton.tag-PickerTagDaily];
        [self.dailyTitleBtn setTitle:[NSString stringWithFormat:@"%@AM",val]
                            forState:UIControlStateNormal];
        for (UIButton *aButton in self.dailyItems) {
            [aButton setSelected:NO];
        }
        [[AlertService sharedCenter] setDailyAlertTime:val];
    }else{
        NSString *val = [self titleForEventAtRow:aButton.tag-PickerTagEvent];
        [self.eventTitleBtn setTitle:[NSString stringWithFormat:NSLocalizedString(@"提前%@分钟提醒", nil),val]
                            forState:UIControlStateNormal];
        for (UIButton *aButton in self.eventItems) {
            [aButton setSelected:NO];
        }
        [[AlertService sharedCenter] setEventAheadTime:val];
    }
    [aButton setSelected:YES];
    [self hideActivityView];
}

-(IBAction)dailyAct:(id)sender
{
    for (UIButton *aButton in self.dailyItems) {
        [aButton setHidden:NO];
    }
    for (UIButton *aButton in self.eventItems) {
        [aButton setHidden:YES];
    }
    
    [self showActivityView];
}

-(IBAction)eventAct:(id)sender
{
    for (UIButton *aButton in self.eventItems) {
        [aButton setHidden:NO];
    }
    for (UIButton *aButton in self.dailyItems) {
        [aButton setHidden:YES];
    }
    
    [self showActivityView];
    
}

- (NSString*)titleForEventAtRow:(NSInteger)row{
    NSString* title = @"30";
    switch (row) {
        case 0:
            title = @"30";
            break;
        case 1:
            title = @"60";
            break;
        case 2:
            title = @"120";
            break;
            
        default:
            break;
    }
    return title;
}

- (NSString*)titleForDailyAtRow:(NSInteger)row{
    NSString* title = @"06:30";
    switch (row) {
        case 0:
            title = @"06:30";
            break;
        case 1:
            title = @"09:00";
            break;
        case 2:
            title = @"12:00";
            break;
            
        default:
            break;
    }
    return title;
}

#pragma mark - ActivityView
-(void)setupActivityView
{
    
    self.activityView.frame = CGRectMake(0, ScreenHeight, self.activityView.frame.size.width, self.activityView.frame.size.height);
    self.shadeView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    
    [self.navigationController.view addSubview:self.shadeView];
    [self.navigationController.view addSubview:self.activityView];
    
    
    self.shadeView.hidden = YES;
    [self.shadeView whenTapped:^{
        [self hideActivityView];
    }];
    
}
-(void)showActivityView{
    if (self.isShowing) {
        return;
    }
    
    [UIView animateWithDuration:0.3 animations:^{
        self.shadeView.hidden = NO;
        self.activityView.frame = CGRectMake(0,
                                             ScreenHeight- self.activityView.frame.size.height,
                                             self.activityView.frame.size.width,
                                             self.activityView.frame.size.height);
        
        self.shadeView.alpha = .2;
    } completion:^(BOOL finished) {
        
        self.show = YES;
    }];
}

-(void)hideActivityView{
    if (!self.isShowing) {
        return;
    }
    
    [UIView animateWithDuration:0.3 animations:^{
        self.shadeView.alpha = 0;
        self.shadeView.hidden = YES;
        self.activityView.frame = CGRectMake(0, ScreenHeight, self.activityView.frame.size.width, self.activityView.frame.size.height);
    } completion:^(BOOL finished) {
        self.show = NO;
    }];
}
-(IBAction)cancelAction:(id)sender
{
    [self hideActivityView];
}

-(IBAction)toggleDaily:(id)sender
{
    [self.tableView beginUpdates];
    if (self.isDailySwitch.isOn) {

        [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:1 inSection:1]]
                              withRowAnimation:UITableViewRowAnimationAutomatic];
    }else{
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:1 inSection:1]]
                              withRowAnimation:UITableViewRowAnimationAutomatic];
    }
    
    [self.tableView endUpdates];
    [AlertService setDailyAlert:self.isDailySwitch.isOn];
}
-(IBAction)toggleEvent:(id)sender
{
    [self.tableView beginUpdates];
    if (self.isEventSwitch.isOn) {
        [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:1 inSection:0]]
                              withRowAnimation:UITableViewRowAnimationAutomatic];
    }else{
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:1 inSection:0]]
                              withRowAnimation:UITableViewRowAnimationAutomatic];
    }
    
    [self.tableView endUpdates];
    [AlertService setEventAlert:self.isEventSwitch.isOn];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger count = 2;
    
    if (section == 0  && !self.isEventSwitch.isOn) {
        count = 1;
    }
    
    if (section == 1  && !self.isDailySwitch.isOn) {
        count = 1;
    }

    return count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    
    if ((indexPath.row == 0) && (indexPath.section==2)) {
        //[[tableView cellForRowAtIndexPath:indexPath] ];
        
        if ([theApp isAppReachable]) {
            HUD.mode = MBProgressHUDModeIndeterminate;
            HUD.labelText = nil;
            [HUD show:YES];
            
            //使用子线程请求服务器数据：调用此方法
            [self performSelectorInBackground:@selector(CheckNewEnterpriseVersionRequest) withObject:nil];
            //[self CheckNewEnterpriseVersionRequest];
        }
        
        
        
    }
    
    if ((indexPath.row == 1) && (indexPath.section==2)) {
        HelpViewController *helpVC = [self.storyboard instantiateViewControllerWithIdentifier:@"helpVC"];
        [self presentViewController:helpVC animated:YES completion:NULL];
    }
    
    
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


- (void)CheckNewEnterpriseVersionRequest
{
    //读当前版本
    NSDictionary *dictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *CFBundleVersion = [dictionary objectForKey:@"CFBundleVersion"];
    
    NSURL *requestUrl = [NSURL URLWithString:APP_PLIST_URL];

    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:requestUrl];
    [request setTimeOutSeconds:20];
    [request setTag:1];
    [request setRequestMethod:@"GET"];
    [request addRequestHeader:@"Content-Type" value:@"text/xml;charset=utf-8"];
    [request setDefaultResponseEncoding:NSUTF8StringEncoding];
    [request startSynchronous];
    if (![request error])
    {
        NSString *xmlResponse = [request responseString];
        NSLog(@"%@",xmlResponse);
        DDXMLDocument *xmlDoc = [[DDXMLDocument alloc] initWithXMLString:xmlResponse options:0 error:nil];
        
        
        NSArray *vArr = [xmlDoc nodesForXPath:@"/plist/dict/array/dict/dict/string[2]" error:nil];

        NSMutableString * v = [NSMutableString stringWithString:[[vArr firstObject] stringValue]];
        
        NSString *vStr = [[v stringByReplacingOccurrencesOfString:@"<string>"withString:@""] stringByReplacingOccurrencesOfString:@"</string>"withString:@""];
        
        NSLog(@"%@",vStr);
        
        
        if ([vStr floatValue] > [CFBundleVersion floatValue])
        {
            [HUD hide:YES];
            [[UIApplication sharedApplication] openURL:[[NSURL alloc]initWithString:APP_DOWNLOAD_URL]];
        }else{
           
            [self performSelectorOnMainThread:@selector(showIsNewVersion:) withObject:nil waitUntilDone:YES];
            
        }

    }
    else
    {
        
    }
    //[pool release];
    //return newVersion;
}
-(void)showIsNewVersion:(id)sender
{
    HUD.mode = MBProgressHUDModeText;
    
    HUD.labelText = NSLocalizedString(@"已是最新版本", nil);
    [HUD show:YES];
    [HUD hide:YES afterDelay:1.6];
}

- (void)showAlertViewWithTitle:(NSString*)title
{
    NSLog(@"show");
}


@end
